package cn.edu.cque.mall.controller;

import cn.edu.cque.mall.entity.Cart;
import cn.edu.cque.mall.entity.Order;
import cn.edu.cque.mall.entity.User;
import cn.edu.cque.mall.service.OrderService;
import org.apache.commons.beanutils.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import java.lang.reflect.InvocationTargetException;
import java.util.List;
import java.util.Map;

/**
 * @ClassName OrderController
 * @Description
 * @Author chen
 * @Date 2020/10/12 0012 9:27
 */
@Controller
@RequestMapping("/order")
public class OrderController{
    @Autowired
    OrderService orderService;

    @RequestMapping("/create-order")
    public ModelAndView createOrder(HttpServletRequest request) {
        ModelAndView modelAndView = new ModelAndView();
        // 1 获取参数
        User user = (User) request.getSession().getAttribute("loginUser");
        Cart cart = (Cart) request.getSession().getAttribute("cart");
        // 2 创建订单
        Order order = orderService.saveOrder(user, cart);
        // 3 将数据存入request域中跳转页面
        modelAndView.addObject("order", order);

        modelAndView.setViewName("/WEB-INF/page/order-info");
        return modelAndView;
    }

    @RequestMapping("/update-order")
    public String updateOrder(HttpServletRequest request) {
        // 1 获取参数
        Map<String, String[]> parameterMap = request.getParameterMap();
        Order order = new Order();
        try {
            BeanUtils.populate(order, parameterMap);
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        } catch (InvocationTargetException e) {
            e.printStackTrace();
        }
        // 2 更新订单
        orderService.updateOrderInfo(order);
        // 3 重定向到订单列表页面
        return "redirect:/order/list";
    }

    @RequestMapping("/list")
    public ModelAndView orderList(HttpServletRequest request) {
        ModelAndView modelAndView = new ModelAndView();
        // 1 从session中获取用户
        User loginUser = (User) request.getSession().getAttribute("loginUser");
        // 1 查询订单列表
        List<Order> orderList = orderService.findAllByUid(loginUser.getId());
        // 2 存储数据
        request.setAttribute("orderList", orderList);
        modelAndView.addObject("orderList", orderList);
        modelAndView.setViewName("/WEB-INF/page/order-list");
        // 3 跳转页面
        return modelAndView;
    }

}
